package self.hoy.demo.cloud.seata.service.impl;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import self.hoy.demo.cloud.seata.dao.OrderDao;
import self.hoy.demo.cloud.seata.entity.TOrder;
import self.hoy.demo.cloud.seata.service.AccountService;
import self.hoy.demo.cloud.seata.service.OrderService;
import self.hoy.demo.cloud.seata.service.StorageService;

import javax.annotation.Resource;

/**
 * @author 三共小不
 * @date 2020/6/20
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private AccountService accountService;

    @Resource
    private StorageService storageService;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减余额->修改订单状态订单
     * @param order
     */
    @Override
    @GlobalTransactional(name = "hoy-create-order", rollbackFor = Exception.class)
    public void create1(TOrder order) {
        log.info("------ 1 Order Service start create order");
        orderDao.create(order);

        log.info("------ 1 Order Service call storage decrease");
        storageService.decrease(order.getProductId(), order.getCount());

        log.info("------ 1 Order service call account decrease");
        accountService.decrease(order.getUserId(), order.getMoney());

        log.info("------ 1 start update Order status");
        orderDao.update(order.getId(), 0);
        log.info("------ 1 after update Order status");

        int a = 1 / (order.getCount() % 2);
    }

    @Override
    public void create2(TOrder order) {
        log.info("------ 2 Order Service start create order");
        orderDao.create(order);

        log.info("------ 2 Order Service call storage decrease");
        storageService.decrease(order.getProductId(), order.getCount());

        log.info("------ 2 Order service call account decrease");
        accountService.decrease(order.getUserId(), order.getMoney());

        log.info("------ 2 start update Order status");
        orderDao.update(order.getId(), 0);
        log.info("------ 2 after update Order status");

        int a = 1 / (order.getCount() % 2);
    }

    @Override
    public void update(Long userId, Integer status) {
        orderDao.update(userId, status);
    }
}
